package czt.ocr.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import czt.ocr.util.httpclient.HttpClientUtils;
import czt.ocr.util.httpclient.HttpResponse;
import lombok.AllArgsConstructor;
import net.sourceforge.tess4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Service
@AllArgsConstructor
public class OcrService {

    private final Tesseract tesseract;

    @Autowired
    private HttpClientUtils httpClientUtils;

    /**
     * 识别图片中的文字
     * @param imageFile 图片文件
     * @return 文字信息
     */
    public String recognizeText(MultipartFile imageFile) throws TesseractException, IOException {

        // 转换
        InputStream sbs = new ByteArrayInputStream(imageFile.getBytes());
        BufferedImage bufferedImage = ImageIO.read(sbs);

        // 对图片进行文字识别
        return tesseract.doOCR(bufferedImage);
    }

    /**
     * 调用远程方法解析图片并返回内容
     * @return 图片内容
     * @throws Exception 异常
     */
    public String parseFile(MultipartFile file) throws Exception {
        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("file", file);
        // 调用远程方法
        HttpResponse response = httpClientUtils.doPost("url",mapParam);
        String body = response.getBody();
        Map<String, Object> map = JSON.parseObject(body);
        String result = map.get("key").toString();
        return result;
    }
}
